package com.scau402.system.controller;



import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.scau402.common.core.domain.AjaxResult;
import com.scau402.common.utils.CustomRedisConfig;
import com.scau402.common.utils.StringUtils;
import com.scau402.config.MockConfig;
import com.scau402.system.domain.Crop;
import com.scau402.system.domain.WmsJadeFeature;
import com.scau402.system.domain.WmsJadeImage;
import com.scau402.system.service.IWmsJadeFeatureService;
import com.scau402.system.service.IWmsJadeImageService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.scau402.common.utils.http.HttpUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/image")
@Slf4j
public class ImageController {

    @Autowired
    private MockConfig mockConfig;

    String url = "http://cyolov8:8001/"; // docker 容器地址

    @GetMapping("/test")
    public String imageApiTest() {
        return HttpUtils.sendGet(url + "test");
    }

    private final IWmsJadeFeatureService jadeFeatureService;

    private final IWmsJadeImageService jadeImageService;

    private final RestTemplate restTemplate;

    public ImageController(IWmsJadeFeatureService jadeFeatureService, IWmsJadeImageService jadeImageService, RestTemplate restTemplate) {
        this.jadeFeatureService = jadeFeatureService;
        this.jadeImageService = jadeImageService;
        this.restTemplate = restTemplate;
    }


    /**
     * 翡翠特区特征
     *
     * params:
     *
     * return:
     *     提取成功信息
     */
    @PreAuthorize("@ss.hasPermi('system:jadeImage:add')")
    @PostMapping("/feature")
    public AjaxResult imageToFeature(@RequestBody String params) throws IOException {
        if (mockConfig.isMockMatchEnabled()) {
            return AjaxResult.success("mock");
        }
        JSONObject paramsJson =  JSON.parseObject(params);
        String data = paramsJson.getString("data");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(data, headers);
        String response = restTemplate.postForObject("http://cyolov8:8001/crop_img_to_feature", request, String.class);
        AjaxResult ajax = AjaxResult.success();
        return ajax.put("msg", response);
    }

    /**
     * 翡翠图片切割
//     * @param params 图片路径
     * @return 分割结果的图片id和保存路径
     * @throws IOException
     */
    @PreAuthorize("@ss.hasPermi('system:jadeImage:add')")
    @PostMapping("/crop")
    public AjaxResult imageCrop(@RequestBody Crop crop) throws IOException {
//        log.info("params: "+params);
        //开启mock数据
        if (mockConfig.isMockCropEnabled()) {
            AjaxResult ajax = AjaxResult.success();
            ajax.put("msg", "mock");
            ajax.put("jadeCount", 2);
            Map<Long, String> resultMap = new HashMap<Long, String>();
            resultMap.put(5981L, "/upload/2023/12/20/2022-10-26_19_13_57_332_20231220213228A148_1.jpg");
            resultMap.put(5898L, "/upload/2023/12/17/2022-10-26_19_13_25_354_20231217220928A077.jpg");
            ajax.put("result", resultMap);
            return ajax;
        }

        // 转换参数图像路径
//        JSONObject paramsJson =  JSON.parseObject(params);
//        log.info("paramsJson: "+paramsJson.toString());
//        System.out.println("getParamsJson: "+paramsJson.get("image_path"));
//        String imagePath = paramsJson.getString("image_path");
        System.out.println("imagePath: /"+crop.getImage_path());
        // Todo :参数缺少一个"/"
        String imagePath = "/"+crop.getImage_path();
        // 开发测试用提取特征
        boolean extractFeature = false;
//        if(paramsJson.containsKey("extract_feature")) {
//            extractFeature = paramsJson.getBoolean("extract_feature");
//        }

        // 调用图像分割接口
        JSONObject postParams = new JSONObject();
        postParams.put("imageUrl", imagePath);
        log.info("imagePath: "+imagePath);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(postParams.toJSONString(), headers);
//        String response = restTemplate.postForObject("http://localhost:9002/crop_img", request, String.class);
        // TODO: 开发完之后改回来
        String response = restTemplate.postForObject("http://cyolov8:8001/crop_img", request, String.class);
        log.info("图像分割接口 response: " + response);
        // 处理返回结果
        JSONObject jsonObject =  JSON.parseObject(response);
        // 检测到的翡翠数量
        int jadeCount = jsonObject.getIntValue("jadeCount");

        AjaxResult ajax = AjaxResult.success();
        if(jadeCount > 0) {
            // 分割的翡翠保存路径
            JSONArray jadeImageUrls = jsonObject.getJSONArray("jadeImagePaths");
            List<String> jadeUrls = jadeImageUrls.toJavaList(String.class);

            JSONArray jadeImageSizesJson = jsonObject.getJSONArray("jadeImageSizes");
            List<Integer> jadeImageSizes = jadeImageSizesJson.toJavaList(Integer.class);

            Map<Long, String> resultMap = new HashMap<Long, String>();

            for(int i=0; i<jadeUrls.size(); i++) {
                // TODO  2023/12/24 17:24: PO的参数不完整
                WmsJadeImage jadeImage = new WmsJadeImage();
                jadeImage.setParentImageUrl(imagePath);
                String jadeImagePath = jadeUrls.get(i).replace("../home/jmsdata/uploadPath", "");
                jadeImage.setImageUrl(jadeImagePath);
                jadeImage.setImageSize(jadeImageSizes.get(i));
                if(jadeImageService.checkUrlExists(jadeImagePath) == 0) {
                    // 保存分割图像到 MYSQL
                    jadeImageService.insertWmsJadeImage(jadeImage);
                    Long jadeImageId = jadeImageService.getJadeImageIdByUrl(jadeImage.getImageUrl());
                    resultMap.put(jadeImageId, jadeImagePath);
                    if(extractFeature == true) {
                        JSONObject object = new JSONObject();
                        object.put("imageId", jadeImageId);
                        object.put("imagePath", jadeImagePath);
                        imageToFeature(object.toString());
                    }
                    ajax.put("result", resultMap);
                    ajax.put("jadeCount", jadeCount); // 检测到的翡翠计数
                } else {
                    ajax.put("该图片已经存在：", jadeImagePath);
                }
            }
        } else if (jadeCount == 0) {
            ajax = AjaxResult.error();
            ajax.put("message", "没有检测到翡翠");
        }
        log.info("crop ajax: " + ajax);
        return ajax;
    }
}
